﻿using PromoOffersCrawler.Crawler.Managers;
using PromoOffersCrawler.Crawler.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PromoOffersCrawler.Web.Managers
{
    public class CrawlerManager
    {
        private static Dictionary<int, WebSiteCrawler> CurrentlyRunningOpertations = new Dictionary<int, WebSiteCrawler>();
        private static Dictionary<int, List<string>> messages = new Dictionary<int, List<string>>();
        public static int GetProgres(int opperationID)
        {
            var opperation = CurrentlyRunningOpertations[opperationID];

            var result = opperation.GetProgres();

            if (result == 100)
            {
                CurrentlyRunningOpertations[opperationID] = null;
            }

            return result;
        }

        public static int RegisterOperation(WebSiteCrawler opperation)
        {
            var id = (CurrentlyRunningOpertations.Keys.Max(x => (int?)x) ?? 0) + 1;

            CurrentlyRunningOpertations[id] = opperation;

            messages[id] = new List<string>();
            
            opperation.NewMessage += opperation_NewMessage;
            opperation.UniqueIdentifier = id;
            return id;
        }

        static void opperation_NewMessage(object sender, EventArgs e)
        {
            var opp = sender as WebSiteCrawler;

            messages[opp.UniqueIdentifier].Add((e as NewMessageEventArgs).Message);
        }

        public static IEnumerable<string> GetMessages(int opperationId)
        {
            return messages[opperationId];
        }
    }
}